package com.skycode7.servlet;

import com.skycode7.bean.NoticeBean;
import com.skycode7.dao.NoticeDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/notice.jsp")
public class NoticeServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            String User = (String) req.getSession().getAttribute("User");
            if (User == null || User.equals("")) {
                resp.sendRedirect("login.jsp");
                return;//页面显示和重定向只能生效一个
            }
            req.setCharacterEncoding("UTF-8");//请求参数类型设置
            String sp = req.getParameter("page");//前端的参数都是String类型
            int page = 1; //转了下情况
            if (sp!= null && sp.equals("")) {//判断是否为数字
                page = Integer.parseInt(sp);//将前端字符数字强制转化为整形
            }
            NoticeDao noticeDao = new NoticeDao();
            List<NoticeBean> list = noticeDao.getList(page);//分页查询
            int totalCount = noticeDao.count();//统计总条数
            int totalPage;
            if (totalCount % 10 == 0) { ///假设有10条数据 和11条  两种情况
                totalPage = totalCount / 10;
            }else {
                totalPage = totalCount / 10 + 1;
            }
            int upPage;
            if (page == 1){
                upPage = 1;
            }else {
                upPage = page - 1;
            }int downPage;
            if (page == totalPage){
                downPage = totalPage;
            }else {
                downPage = page + 1;
            }req.setAttribute("curPage", page);
            req.setAttribute("upPage", upPage);
            req.setAttribute("downPage", downPage);
            req.setAttribute("totalPage", totalPage);
            req.setAttribute("totalCount", totalCount);
            req.setAttribute("list", list);//通过req将list数据传递给前端
            //属于额外知识
            //getRequestDispatcher决定webapp目录下那个文件显示
            req.getRequestDispatcher("WEB-INF/notice.jsp").forward(req, resp);
        }
    }

